
import { assetsDB } from '@/indexDB/index'
import { DEFAULT_CATEGORY_LIST } from '@/views/category/model'
import { ref } from 'vue'
import BuildTreeWorker from '@/views/category/BuildTree?worker'

import type { CategoryLevel } from './types'

export interface CategoryItem {

  id?: string | number

  parentId?: string | number // 父级主键
  /**
   * @deprecated 已弃用，请使用 id 来代替。
   */
  code?: string // 旧主键
  /**
   * @deprecated 已弃用，请使用 parentId 来代替。
   */
  parentCode?: string // 旧父级主键
  name: string
  level: CategoryLevel
}

export const categoryList = ref<CategoryItem[]>([])

export const initCategoryDB = async () => {
  const arr = await assetsDB.categoryList.toArray()
  if (!arr.length) {

    await assetsDB.categoryList.bulkPut(DEFAULT_CATEGORY_LIST)
    // 顺便初始化以便全局使用
    console.log('--分类初始化成功');
    updateCategoryList()
    updateCategoryTree()
  } else {
    updateCategoryList()
    updateCategoryTree()
  }
}

export const updateCategoryList = async () => {
  categoryList.value = await assetsDB.categoryList.toArray()
  return Promise.resolve(categoryList.value)
}

export interface TreeNode extends CategoryItem {
  children?: TreeNode[]
  value?: number //该分类的市值
}

export const categoryTree = ref<TreeNode[]>([])

export const updateCategoryTree = async () => {
  const worker = new BuildTreeWorker()
  if (!categoryList.value.length) {
    await updateCategoryList()
  }

  worker.postMessage(JSON.stringify(categoryList.value))
  worker.onmessage = (e) => {
    categoryTree.value = e.data
  }
}